package com.aoxon.cargo.component.n;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aoxon.cargo.R;
import com.aoxon.cargo.activity.PurGoodsPagerActivity;
import com.aoxon.cargo.bean.Cloth;
import com.aoxon.cargo.cache.PurCache;
import com.aoxon.cargo.component.MyLoadCloth;
import com.aoxon.cargo.database.DataService;
import com.aoxon.cargo.loader.FileLoader;
import com.aoxon.cargo.service.ClickGoodsService;
import com.aoxon.cargo.service.MyServiceFactory;
import com.aoxon.cargo.state.MyStateUtil;
import com.aoxon.cargo.util.EnvironmentUtil;
import com.aoxon.cargo.util.ExecutorUtil;
import com.aoxon.cargo.util.ToastUtil;
import com.aoxon.cargo.view.MyScrollView;

public class WaterFallGoodsView implements MyScrollView.OnScrollListener {

	private FileLoader myImageLoader = new FileLoader(300, 300, true);

	private Activity activity;
	private LayoutInflater layoutInflater;
	private TextView tvLoading;
	private ProgressBar progressBar;
	private MyScrollView myScrollView;
	private List<?> list;
	public int length = 12; // 每次加载的个数
	public int startIndex = 0; // 显示的总个数
	private boolean isLoading = false;
	private boolean isReachLast = false;
	public boolean cancleLoad = false;
	private View timeBox;
	private ClickGoodsService clickGoodsService = (ClickGoodsService) MyServiceFactory
			.getInstance(MyServiceFactory.CLICK_GOODS);
	private DataService dataService;

	//
	private Map<Integer, View> viewMap;
	// srollview 内的根布局
	private LinearLayout rootLayout;
	// 第一列的布局
	private LinearLayout firstColumn;
	// 第二列的布局
	private LinearLayout secondColumn;
	// 当前第一列的高度
	private int firstColumnHeight;
	// 当前第二列的高度
	private int secondColumnHeight;
	//
	public int loadType = MyLoadCloth.INDEX_NEW;

	private int width;
	private boolean isIndex = false;

	public WaterFallGoodsView(Activity activity, List<?> list) {
		this.activity = activity;
		this.list = list;
		this.layoutInflater = LayoutInflater.from(activity.getBaseContext());
		this.dataService = new DataService(activity);

		tvLoading = (TextView) activity.findViewById(R.id.tvListBottom);
		progressBar = (ProgressBar) activity.findViewById(R.id.pbListBottom);
		// rlListBottom = (RelativeLayout)
		// activity.findViewById(R.id.rlListBottom);

		viewMap = new HashMap<Integer, View>();
		myScrollView = (MyScrollView) activity
				.findViewById(R.id.msvPurGridShowGoodsNew);
		firstColumn = (LinearLayout) activity.findViewById(R.id.first_column);
		secondColumn = (LinearLayout) activity.findViewById(R.id.second_column);

		myScrollView.getView();
		myScrollView.setOnScrollListener(this);

		DisplayMetrics metric = new DisplayMetrics();
		activity.getWindowManager().getDefaultDisplay().getMetrics(metric);
		width = metric.widthPixels; // 屏幕宽度（像素）
	}

	public WaterFallGoodsView(Activity activity, List<?> list, View timeBox,
			boolean isIndex) {
		this.list = list;
		this.isIndex = isIndex;
		this.layoutInflater = LayoutInflater.from(activity);
		this.activity = activity;
		this.timeBox = timeBox;
		myScrollView = (MyScrollView) layoutInflater.inflate(
				R.layout.pur_grid_show_goods_new, null);
		tvLoading = (TextView) myScrollView.findViewById(R.id.tvListBottom);
		progressBar = (ProgressBar) myScrollView
				.findViewById(R.id.pbListBottom);
		rootLayout = (LinearLayout) myScrollView.findViewById(R.id.root_layout);
		// rlListBottom = (RelativeLayout)
		// activity.findViewById(R.id.rlListBottom);

		viewMap = new HashMap<Integer, View>();
		firstColumn = (LinearLayout) myScrollView
				.findViewById(R.id.first_column);
		secondColumn = (LinearLayout) myScrollView
				.findViewById(R.id.second_column);
		myScrollView.getView();
		myScrollView.setOnScrollListener(this);

		DisplayMetrics metric = new DisplayMetrics();
		activity.getWindowManager().getDefaultDisplay().getMetrics(metric);
		width = metric.widthPixels; // 屏幕宽度（像素）
	}

	/**
	 * 清空所有列中的子项显示和列表数据
	 */
	public void clearView() {
		startIndex = 0;
		isReachLast = false;
		list.clear();
		viewMap.clear();
		firstColumn.removeAllViews();
		secondColumn.removeAllViews();
		firstColumnHeight = secondColumnHeight = 0;
	}

	/**
	 * 加载数据的操作
	 */
	public void loadData() {
		if (!isReachLast && !isLoading) {
			tvLoading.setText("加载中...");
			progressBar.setVisibility(View.VISIBLE);
			ExecutorUtil.getCachedExecutorService().submit(new Runnable() {

				@Override
				public void run() {
					Message msg = new Message();
					// final boolean net =
					// EnvironmentUtil.checkNetState(activity);
					final boolean net = true;
					if (net) {
						try {
							isLoading = true;

							if (cancleLoad) {
								return;
							}

							if (toLoad.doLoad()) {
								msg.what = MyStateUtil.LIST_CHANGE;
							} else {
								// 查找不到数据的情况
								isReachLast = true;
								msg.what = MyStateUtil.LIST_IS_REACH_LAST;
							}
						} catch (Exception e) {
							e.printStackTrace();
							msg.what = MyStateUtil.ERROR_NET_CONNECTION;
						}
					} else {
						// 若无网络连接
						msg.what = MyStateUtil.NOT_NET_CONNECTION;
					}
					myHandler.sendMessage(msg);
				}
			});
		}
	}

	Handler myHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			progressBar.setVisibility(View.GONE);
			switch (msg.what) {
			case MyStateUtil.LIST_CHANGE:
				Log.i("listChange",
						"------------------listChange--------------------");
				tvLoading.setText("向上拉加载数据");
				if (cancleLoad) {
					break;
				}
				//
				redrawView();
				// adapter.notifyDataSetChanged();
				break;
			case MyStateUtil.LIST_IS_REACH_LAST:
				tvLoading.setText("没有相应数据咯～");
				break;
			case MyStateUtil.NOT_NET_CONNECTION:
				tvLoading.setText("无网络连接～");
				break;
			case MyStateUtil.ERROR_NET_CONNECTION:
				tvLoading.setText("向上拉加载数据");
				ToastUtil.show(activity, "网络连接异常");
				break;
			default:
				break;
			}
			isLoading = false;
			super.handleMessage(msg);
		}
	};

	public void notifyDataChange() {
		redrawView();
	}

	// -------------------------------------------------
	private int sIndex = 0;

	// private List<Cloth> newList;
	/**
	 * 重绘ui
	 */
	private void redrawView() {
		if (startIndex > 0) {
			sIndex = list.size() - length;
			if (sIndex < 0) {
				sIndex = 0;
			}
		}
		// newList = new ArrayList<Cloth>();
		// for (int i = sIndex; i < list.size(); i++) {
		// newList.add((Cloth)list.get(i));
		// }
		// final List<?> newList = list.subList(sIndex, list.size());
		// for (int i = 0; i < newList.size(); i++) {
		for (int i = sIndex; i < list.size(); i++) {
			if (isIndex) {
				findColumnToAdd(timeBox, 300);
				isIndex = false;
				continue;
			}
			final int position = i;
			// final Cloth cloth = (Cloth)newList.get(i);
			final Cloth cloth = (Cloth) list.get(i);
			View itemView = layoutInflater.inflate(
					R.layout.pur_grid_goods_item_new, null);
			// 图片
			ImageView imageView = (ImageView) itemView
					.findViewById(R.id.ivPurGoodsGridItemNew);
			imageView.setImageResource(R.drawable.loading);
			ProgressBar pBar = (ProgressBar) itemView
					.findViewById(R.id.pbPurGoodsGridItem);
			String path = "";
			if (cloth.getPictures() != null) {
				if (cloth.getPictures().size() <= 1) {
					path = cloth.getPictures().get(0).getPictureUrl() + "m.png";
				} else {
					path = cloth.getPictures().get(0).getPictureUrl() + "m.png";
				}
			}
			myImageLoader.displayImage(path, imageView, pBar, false);
			// 设置图片的高度为图片的宽度
			RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) imageView
					.getLayoutParams();
			params.height = width / 2;
			imageView.setLayoutParams(params);
			//
			// ImageView bottomImageView = (ImageView)
			// itemView.findViewById(R.id.ivItemBottom);
			// RelativeLayout.LayoutParams params2 =
			// (RelativeLayout.LayoutParams) bottomImageView.getLayoutParams();
			// params.width = width;
			// bottomImageView.setLayoutParams(params2);

			TextView tvGoodsName = (TextView) itemView
					.findViewById(R.id.tvGoodsName);
			tvGoodsName.setText(cloth.getClothName());
			TextView tvGoodsPrice = (TextView) itemView
					.findViewById(R.id.tvGoodsPrice);
			if (cloth.getPrices() != null) {
				tvGoodsPrice.setText("￥" + cloth.getPrices().get(0).getPrice());
			}
			TextView tvGoodsCollectNum = (TextView) itemView
					.findViewById(R.id.tvGoodsCollectNum);
			tvGoodsCollectNum.setText(cloth.getCollectedNum() + "");
			// itemView.setPadding(5, 5, 5, 5);
			findColumnToAdd(itemView, 300);
			viewMap.put(cloth.getClothId(), itemView);
			// 添加点击事件
			itemView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					try {
						PurCache.cloth = cloth;
						final int clothsId = cloth.getClothId();
						ExecutorUtil.getCachedExecutorService().submit(
								new Runnable() {

									@Override
									public void run() {
										clickGoodsService.execute(clothsId);
									}
								});
						Intent intent = new Intent(activity,
								PurGoodsPagerActivity.class);
						MyLoadCloth.waterFallGoodsView = WaterFallGoodsView.this;
						MyLoadCloth.setExtra(intent, list.size(), length,
								loadType, position, list);
						activity.startActivityForResult(intent, 1);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
		}
	}

	/**
	 * 找到此时应该添加图片的一列。原则就是对三列的高度进行判断，当前高度最小的一列就是应该添加的一列。
	 * 
	 * @param imageView
	 * @param imageHeight
	 * @return 应该添加图片的一列
	 */
	private void findColumnToAdd(View itemView, int itemHeight) {
		Log.i("ps", "firstColumnHeight:" + firstColumnHeight
				+ ", secondColumnHeight:" + secondColumnHeight + ", w："
				+ itemView.getWidth() + ", h:" + itemView.getHeight());
		if (firstColumnHeight <= secondColumnHeight) {
			// imageView.setTag(R.string.border_top, firstColumnHeight);
			firstColumnHeight += itemHeight;
			// imageView.setTag(R.string.border_bottom, firstColumnHeight);
			firstColumn.addView(itemView);
			Log.i("add", "firstColumn......:" + itemHeight);
		} else {
			// imageView.setTag(R.string.border_top, secondColumnHeight);
			secondColumnHeight += itemHeight;
			// imageView.setTag(R.string.border_bottom, secondColumnHeight);
			secondColumn.addView(itemView);
			Log.i("add", "secondColumn......");
		}
	}

	/**
	 * 改变收藏数
	 * 
	 * @param clothId
	 * @param collectNum
	 */
	public void updateCollectNum(int clothId, int collectNum) {
		View itemView = viewMap.get(clothId);
		if (itemView != null) {
			TextView tvGoodsCollectNum = (TextView) itemView
					.findViewById(R.id.tvGoodsCollectNum);
			tvGoodsCollectNum.setText(collectNum + "");
		}
	}

	// -------------------------------------------------
	public interface ToLoad {

		public boolean doLoad() throws Exception;
	}

	private ToLoad toLoad;

	public void setToLoad(ToLoad toLoad) {
		this.toLoad = toLoad;
	}

	// -----------------------------------------------
	@Override
	public void onBottom() {
		loadData();
	}

	@Override
	public void onTop() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onScroll() {

	}

	// 即将到达底部（2/3处）
	@Override
	public void onWillToBottom() {
		// loadData();
	}

	public void setListFlag(int flag) {
		myScrollView.setVisibility(flag);
	}

	public View getView() {
		return myScrollView;
	}

	public LinearLayout getRootLayout() {
		return rootLayout;
	}

}
